<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      #calendar {
        display: flex;
        flex-wrap: wrap;
        border: 1px solid;
        width: 280px;
      }
      #calendar div {
        box-sizing: border-box;
        width: 40px;
        height: 40px;
        border: 1px solid;
        display: flex;
        justify-content: center;
        align-items: center;
      }
    </style>
  </head>
  <body>
    <div id="calendar">
      <div>一</div>
      <div>二</div>
      <div>三</div>
      <div>四</div>
      <div>五</div>
      <div>六</div>
      <div>日</div>
    </div>
    <script>
      function createCalendar(elem, year, month) {
        // 获取当前月第一天是星期几
        const w1 = new Date(year, month - 1, 1).getDay() || 7;
        // 获取当前月最后一天是星期几
        const w2 = new Date(year, month, 0).getDay() || 7;
        // 当前月有多少天
        const d1 = new Date(year, month, 0).getDate();

        // 获取上个月的最后一天
        const d2 = new Date(year, month - 1, 0).getDate();

        let str = "";
        // 开始
        for (let i = d2 - w1 + 2; i <= d2; i++) {
          str += `<div style="color:red;">${i}</div>`;
        }
        // 中间
        for (let i = 1; i <= d1; i++) {
          str += `<div>${i}</div>`;
        }
        // 结束
        for (let i = 1; i < 7 - w2 + 1; i++) {
          str += `<div style="color:red;">${i}</div>`;
        }

        elem.innerHTML += str;
      }
      createCalendar(document.getElementById("calendar"), 2023, 9);
    </script>
  </body>
</html>
